import React, { PureComponent } from "react";
import { Map } from 'react-amap';
import { getConfig } from '../../../../config';

const config = getConfig();
const mapKey = config.mapKey;


class PickPostion extends React.Component {
  constructor() {
    super();
    this.loadUI();
  }

  loadUI() {
    window.AMapUI.loadUI(['misc/PositionPicker'], (PositionPicker) => {
      this.initPage(PositionPicker);
    })
  }

  initPage(PositionPicker) {
    const map = this.props.__map__;
    const _this = this.props;
    const originPos = this.props.originPos;

    const positionPicker = new PositionPicker({
      mode:'dragMarker',//设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
      map:map//依赖地图对象
    });

    if(originPos.lng && originPos.lat){
      positionPicker.start(new AMap.LngLat(originPos.lng, originPos.lat));
    }else{
      positionPicker.start(map.getBounds().getSouthWest());
    }
    // {Q: 30.281677835395346, N: 120.10945902612309, lng: 120.109459, lat: 30.281678}


    //
    positionPicker.on('success', function(positionResult) {
      console.log('pp',positionResult.position);
      _this.setPosition(positionResult.position);

    });

    positionPicker.on('fail', function(positionResult) {
      // console.log('选点失败');
    });



  }

  render() {
    return null;
  }
}

const initCallback = () => {
  console.log("AMapUI Loaded Done")
}


export default class Maps extends PureComponent {
  constructor(props) {
    super(props);

  }

  componentDidMount() {

  }

  handleSetPostion = (value) =>{
    this.props.setPosition(value);
  }

  render() {
    const { originPos } = this.props;
    const plugins = [
      // 'MapType',
      'Scale',
      // 'OverView',
      // 'ControlBar', // v1.1.0 新增
      {
        name: 'ToolBar',
        options: {
          visible: true,  // 不设置该属性默认就是 true
        },
      }
    ]
    return (
      <div style={{height:500,width:'100%'}}>
        <Map amapkey={mapKey}
             zoom={14}
             useAMapUI={initCallback}
             plugins={plugins}
        >
          <PickPostion setPosition={this.handleSetPostion} originPos={originPos}/>
        </Map>
      </div>
    );
  }
}

